import { Body, Injectable, UnauthorizedException } from '@nestjs/common';

import { JwtService } from '@nestjs/jwt';
import md5 from 'md5';

import { UserService } from '../user/user.service';

import { UpdateAuthDto } from './dto/update-auth.dto';

@Injectable()
export class AuthService {
    constructor(
        private readonly userService: UserService,
        private readonly jwyService: JwtService,
    ) {}

    async login(@Body() body: any) {
        const user = await this.userService.findByUsername(body.username);
        const password = md5(body.password).toUpperCase();
        console.log(password);

        if (user.password !== password) {
            throw new UnauthorizedException('');
        }
        const payload = { username: user.username, sub: user.id };
        const data = {
            token: await this.jwyService.signAsync(payload),
        };
        return data;
    }

    findAll() {
        return `This action returns all auth`;
    }

    findOne(id: number) {
        return `This action returns a #${id} auth`;
    }

    update(id: number, updateAuthDto: UpdateAuthDto) {
        return `This action updates a #${id} auth`;
    }

    remove(id: number) {
        return `This action removes a #${id} auth`;
    }
}
